
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginValidationFilter implements Filter {

  protected FilterConfig filterConfig;
  public LoginValidationFilter() {
  }

  public void destroy() {
    filterConfig=null;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req=(HttpServletRequest)request;
    HttpServletResponse resp=(HttpServletResponse)response;
    HttpSession session=req.getSession();
    String reqURL=req.getServletPath();
    //登录处理程序LoginServlet不需要过滤
    //登录页面login.html不需要过滤
    //出错提示页面loginError.html
    String loginMess = (String)session.getAttribute("login");
    if(!(reqURL.equals("/ls")|| reqURL.equals("/login.html") || reqURL.equals("/loginError.html"))){
      //对于已经登录的用户，session中存储的登录信息为（"login","true"）。
      if(loginMess == null || !loginMess.equals("true")){
        resp.sendRedirect(req.getContextPath() +
          "/loginError.html");
        return;
      }
    }
    chain.doFilter(request, response);
  }

  public void init(FilterConfig fConfig) throws ServletException {
    this.filterConfig=fConfig;
  }
}
